<template>
  <div class="customers-view">
    <h1>客户信息管理</h1>
    <div class="customer-controls">
      <div class="search-container">
        <input v-model="searchQuery" placeholder="搜索客户..." class="search-input" @keyup.enter="fetchUsers">
        <button @click="showAddModal = true" class="add-button">+ 添加客户</button>
      </div>
    </div>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else class="customer-list">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>地址</th>
            <th>电话</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in filteredUsers" :key="user.userId">
            <td>{{ user.userId }}</td>
            <td>{{ user.username }}</td>
            <td>{{ user.email || "-" }}</td>
            <td>{{ user.address || "-" }}</td>
            <td>{{ user.phone || "-" }}</td>
            <td class="actions">
              <button @click="editUser(user)" class="edit-btn">编辑</button>
              <button @click="confirmDelete(user.userId)" class="delete-btn">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div v-if="showAddModal" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeModal">&times;</span>
        <h2>{{ editingUser ? "编辑用户" : "添加新用户" }}</h2>
        <div class="form-group">
          <label>用户名 <span class="required">*</span></label>
          <input v-model="currentUser.username" type="text" required>
        </div>
        <div class="form-group">
          <label>{{ editingUser ? "新密码" : "密码" }}</label>
          <input v-model="currentUser.password" type="password" :placeholder="editingUser ? '留空则不修改' : ''">
        </div>
        <div class="form-group">
          <label>邮箱</label>
          <input v-model="currentUser.email" type="email">
        </div>
        <div class="form-group">
          <label>地址</label>
          <input v-model="currentUser.address" type="text">
        </div>
        <div class="form-group">
          <label>电话</label>
          <input v-model="currentUser.phone" type="tel">
        </div>
        <div class="modal-actions">
          <button @click="saveUser" class="save-btn" :disabled="saving">{{ saving ? "处理中..." : editingUser ? "更新" : "保存" }}</button>
          <button @click="closeModal" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'CustomersView',
  setup() {
    const users = ref([]);
    const searchQuery = ref('');
    const showAddModal = ref(false);
    const editingUser = ref(null);
    const loading = ref(false);
    const saving = ref(false);
    const errorMessage = ref('');

    // 包含 address 和 phone 字段，与后端一致
    const currentUser = ref({
      userId: null,
      username: '',
      password: '',
      email: '',
      address: '',
      phone: ''
    });

    const API_BASE_URL = 'http://localhost:8080/healtheat208';
    const api = axios.create({ baseURL: API_BASE_URL, headers: { 'Content-Type': 'application/json' } });

    // 获取用户列表
    const fetchUsers = async () => {
      loading.value = true;
      try {
        const response = await api.get('/User/list');
        users.value = response.data;
      } catch (error) {
        handleError(error, '获取用户列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 错误处理统一函数
    const handleError = (error, message) => {
      console.error(message, error);
      const errorMsg = error.response?.data?.message || '操作失败，请联系管理员';
      alert(`${message}: ${errorMsg}`);
    };

    // 保存用户
    const saveUser = async () => {
      if (!currentUser.value.username) {
        alert('用户名不能为空');
        return;
      }
      saving.value = true;
      try {
        const request = editingUser.value 
          ? api.put('/User/update', currentUser.value) 
          : api.post('/User/add', currentUser.value);
        
        await request;
        alert('操作成功');
        await fetchUsers();
        closeModal();
      } catch (error) {
        handleError(error, editingUser.value ? '更新用户失败' : '添加用户失败');
      } finally {
        saving.value = false;
      }
    };

    // 编辑用户
    const editUser = (user) => {
      currentUser.value = { ...user, password: '' }; // 保留 address 和 phone
      editingUser.value = true;
      showAddModal.value = true;
    };

    // 删除用户
    const deleteUser = async (userId) => {
      if (!userId) return handleError(new Error('无效用户ID'), '删除用户失败');
      try {
        await api.delete(`/User/delete/${userId}`);
        alert('用户删除成功');
        users.value = users.value.filter(user => user.userId !== userId);
      } catch (error) {
        handleError(error, '删除用户失败');
      }
    };

    onMounted(fetchUsers);

    const filteredUsers = computed(() => {
      const query = searchQuery.value.toLowerCase();
      return users.value.filter(user => 
        user.username.toLowerCase().includes(query) ||
        user.email.toLowerCase().includes(query) ||
        user.address.toLowerCase().includes(query) ||
        user.phone.toLowerCase().includes(query) ||
        user.userId.toString().includes(query)
      );
    });

    const closeModal = () => {
      showAddModal.value = false;
      editingUser.value = null;
      currentUser.value = { userId: null, username: '', password: '', email: '', address: '', phone: '' };
    };

    return {
      users, searchQuery, filteredUsers, showAddModal, editingUser, currentUser,
      loading, saving, errorMessage, editUser, confirmDelete: deleteUser,
      saveUser, closeModal, fetchUsers
    };
  }
}
</script>

<style scoped>
/* 样式部分保持不变 */
.customers-view {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.customer-controls {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.search-container {
  display: flex;
  gap: 10px;
  width: 100%;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  flex-grow: 1;
  max-width: 400px;
}

.add-button {
  padding: 8px 16px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
}

.add-button:hover {
  background-color: #218838;
}

.loading {
  padding: 20px;
  text-align: center;
  color: #666;
}

.customer-list {
  overflow-x: auto;
}

.customer-list table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.customer-list th,
.customer-list td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.customer-list th {
  background-color: #f8f9fa;
  position: sticky;
  top: 0;
}

.actions {
  display: flex;
  gap: 8px;
}

.edit-btn {
  padding: 5px 10px;
  background-color: #17a2b8;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.edit-btn:hover {
  background-color: #138496;
}

.delete-btn {
  padding: 5px 10px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.delete-btn:hover {
  background-color: #c82333;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 25px;
  border-radius: 8px;
  width: 500px;
  max-width: 95%;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.close {
  position: absolute;
  top: 15px;
  right: 20px;
  font-size: 24px;
  cursor: pointer;
  color: #aaa;
}

.close:hover {
  color: #333;
}

.form-group {
  margin-bottom: 18px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: bold;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.required {
  color: #dc3545;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 25px;
}

.save-btn {
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  min-width: 80px;
}

.save-btn:hover:not(:disabled) {
  background-color: #218838;
}

.save-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.cancel-btn {
  padding: 10px 20px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #5a6268;
}
</style>